package com.hui.intercepter;

import com.hui.entity.User;
import com.hui.service.ResourceService;
import com.hui.service.UserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * ssm 拦截器
 * 也就是用来判断是否有权限
 * HandlerInterceptorAdapter类的preHandle()在执行controller对应访问方法前执行,也就是在这个方法里面做权限判断,返回false后权限验证失败,返回true的话进入controller对应的访问方法
 */
public class InterFaceIntercepter extends HandlerInterceptorAdapter {
    private static String [] urls = {"login"};

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ResourceService resourceService;
    //筛选静态资源
    public static boolean checkUrl(String requestname) {
        if (requestname.equalsIgnoreCase("loginTest")||requestname == null || requestname.equals("")||requestname.equalsIgnoreCase("login")||requestname.equalsIgnoreCase("logout")) {
            return true;
        }
        if (requestname.endsWith(".jsp")||requestname.endsWith(".js") || requestname.endsWith(".css") || requestname.endsWith(".jpg")||requestname.endsWith(".vue")) {
            return true;
        }
        for (int i = 0; i < urls.length; i++) {
            if (urls[i].equals(requestname)) {
                return true;
            }
        }
        return false;
    }
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //TODO 权限验证，验证当前用户是否拥有当前请求这个权限（不验证是否有session）
        HttpSession session = request.getSession();

        //1.获取当前请求的名字 路径判断是否是被拦截的
        String uri = request.getRequestURI();
        String contextpath = request.getContextPath();
        String requestname = uri.substring(contextpath.length()+1, uri.length());
        //动态获取项目的网络地址
        String basepath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextpath+"/";
        if(checkUrl(requestname)){//不验证
            return true;
        }

        //验证用户是否登录 存用户的session不一样
        Subject currentUser = SecurityUtils.getSubject();
        //获取到用户
        User user = (User) currentUser.getPrincipals().getPrimaryPrincipal();
//        UserRole ur =userRoleService.getUserRoleById(user.getId());
//        Integer roleId =ur.getRoleId();
        //根据roleId获取到对应的权限
//        List<Resource> resList =resourceService.

//        Object obj = session.getAttribute("users");
//        if(obj==null){
//            response.sendRedirect(basepath+"index.jsp");
//            return false;
//        }
        //某些请求（比如修改自己的基本信息，退出登录...），是只要求登录就可以访问，而没有纳入权限管理范围的
        //对于这部分请求，应该只做登录验证，而不进入权限验证范围
//        ServletContext application = session.getServletContext();
//        List<String> allurl = (List<String>) application.getAttribute("allurl");
//        if(!allurl.contains(requestname)){
//            return true;
//        }
        //如果程序执行到这里，用户已经登录，并且当前请求不是请求的静态资源
        //所以这里需要开始权限判断,判断当前用户是否拥有当前请求的权限
//        Users users = (Users) obj;
//        if(users.getRole()==null){
//            response.sendRedirect(basepath+"nopriviliage.jsp");
//            return false;
//        }
//        //得到当前用户所拥有的的所有权限信息
//        List<Priviliage> prilist = users.getRole().getPrilist();
//        if(!checkpri(prilist, requestname)){
//            response.sendRedirect(basepath+"nopriviliage.jsp");
//            return false;
//        }
//        return true;
//    }
//    public static boolean checkpri(List<Priviliage> prilist,String requestname){
//        for (int i = 0; i < prilist.size(); i++) {
//            Priviliage pri = prilist.get(i);
//            if(pri.getPriUrl()!=null&&pri.getPriUrl().equals(requestname)){
//                return true;
//            }
//        }
//        response.sendRedirect("view/unauthorized.jsp");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
